package com.botao.cms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.botao.cms.pojo.Notice;
import com.botao.cms.service.NoticeService;
import com.botao.cms.utils.AjaxResult;
import com.botao.cms.utils.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
public class NoticeController {
    @Autowired
    NoticeService noticeService;

    @GetMapping(path = {"admin/sys/advice", "admin/sys/advice.html"})
    public String sysAdvice() {
        return "admin/sys/advice";
    }

    @ResponseBody
    @PostMapping("admin/sys/advice/add")
    public AjaxResult addAdvice(String title, String content) {
        if ("".equals(title) | "".equals(content)) {
            return AjaxResult.error(501, "参数为空");
        }
        boolean save = false;
        try {
            save = noticeService.save(new Notice(UUIDUtil.getuuid(), title, content, new Date()));
        } catch (Exception e) {
            return AjaxResult.error(500, "内容非法，请检查！");
        }
        return save ? AjaxResult.success() : AjaxResult.error();
    }


    @GetMapping(path = {"admin/office/advice","admin/office/advice.html"})
    public String adviceListPage() {
        return "admin/office/information";
    }

    @ResponseBody
    @RequestMapping("advice/list")
    public AjaxResult getAdvices(Long currentPage, Long pageSize) {
        Page<Notice> page = noticeService.page(new Page<Notice>(currentPage, pageSize), new QueryWrapper<Notice>().orderByDesc("created"));
        List<Notice> noticeList = page.getRecords();
        HashMap<String, Object> map = new HashMap<>();
        long current = page.getCurrent();
        long total = page.getTotal();
        long size = page.getSize();
        boolean hasNext = page.hasNext();
        map.put("noticeList", noticeList);
        map.put("current", current);
        map.put("total", total);
        map.put("pageSize", size);
        map.put("hasNext", hasNext);
        return AjaxResult.success(map);
    }
}
